<template>
    <f7-page @page:beforein="pageBeforeIn">
        <f7-navbar>
            <f7-nav-left>
                <f7-link @click="back">
                    <f7-icon icon="icon-back" style="margin-left:15px;"></f7-icon>
                </f7-link>
            </f7-nav-left>
            <f7-nav-title title="修改数值"></f7-nav-title>
        </f7-navbar>
        <f7-block strong inset style="margin-top:5px; margin-bottom:5px;">
            <f7-row style="margin-bottom:5px;">
                <f7-col width="30">
                    <span>标段</span>
                </f7-col>
                <f7-col width="70">
                    <span>{{qualityMeasureProblem && $store.state.global.bidSectionMap[qualityMeasureProblem.bid_section_id].bid_section_name
                    }}</span>
                </f7-col>
            </f7-row>
            <f7-row style="margin-bottom:5px;">
                <f7-col width="30">
                    <span>位置</span>
                </f7-col>
                <f7-col width="70">
                    <span>{{qualityMeasureProblem && qualityMeasureProblem.building_name}}</span>
                    <span>{{qualityMeasureProblem && qualityMeasureProblem.unit_name + '单元'}}</span>
                    <span>{{qualityMeasureProblem && qualityMeasureProblem.floor_name}}</span>
                    <span>{{qualityMeasureProblem && qualityMeasureProblem.room_name}}</span>
                </f7-col>
            </f7-row>
            <f7-row style="margin-bottom:5px;">
                <f7-col width="30">
                    <span>检查项</span>
                </f7-col>
                <f7-col width="70">
                    <span>{{qualityMeasureProblem && $store.state.global.problemClassMap[$store.state.global.problemClassMap[qualityMeasureProblem.item_id].parent_problem_class_id].problem_class_name}}</span>
                    <br />
                    <span>{{qualityMeasureProblem && $store.state.global.problemClassMap[qualityMeasureProblem.item_id].problem_class_name}}</span>
                </f7-col>
            </f7-row>
            <f7-row style="margin-bottom:5px;">
                <f7-col width="30">
                    <span>整改人</span>
                </f7-col>
                <f7-col width="70">
                    <span>{{form.repair && $store.state.global.userMap[form.repair].realname}}</span>
                </f7-col>
            </f7-row>
            <f7-row style="margin-bottom:5px;">
                <f7-col width="30">
                    <span>抄送人</span>
                </f7-col>
                <f7-col width="70">
                   <f7-row v-for="(cc, i) in form.ccs" :key="cc" v-if="i % 3 == 0">
	                    <f7-col v-for="j in 3" :key="form.ccs[i + j - 1]">
	                        <span v-if="i + j - 1 < form.ccs.length">
	                           {{$store.state.global.userMap[form.ccs[i + j - 1]].realname}}
	                        </span>
	                    </f7-col>
	                </f7-row>
                </f7-col>
            </f7-row>
        </f7-block>
        <f7-block strong inset style="margin-top:5px; margin-bottom:5px;">
            <f7-row style="margin-bottom:5px;">
                <f7-col width="30">
                    <span>实测点数</span>
                </f7-col>
                <f7-col width="70">
                    <f7-stepper fill :value="form.measurePoints" :step="1" :min="0" :max="99"
                        :autorepeat="true" :wraps="true" :manual-input-mode="true"
                        @stepper:change="pointCountChange()">
                    </f7-stepper>
                </f7-col>
            </f7-row>
            <f7-row style="margin-bottom: 5px;">
                <f7-col width="30">
                    <span>爆点数值</span>
                    <f7-link @click="addProblemValue" v-if="qualityMeasureProblem.drawing_file.length == 0">
                        <f7-icon f7="add_round"></f7-icon>
                    </f7-link>
                </f7-col>
                <f7-col width="70" v-if="qualityMeasureProblem.drawing_file.length > 0">
                    <f7-button @click="openHousePoint">在户型图上标记</f7-button>
                    <f7-row style="margin-top:10px; margin-bottom:10px;"
                        v-for="(value, i) in form.problemValues" v-if="i % 5 == 0" :key="i">
                        <f7-col v-for="j in 5" :key="i + '-' + j">
                            <span>{{(i + j - 1 < form.problemValues.length) ? form.problemValues[i + j - 1].val: ''}}</span>
                        </f7-col>
                    </f7-row>
                </f7-col>
                <f7-col width="70" v-else>
                    <f7-row style="margin-top:10px; margin-bottom:10px;"
                        v-for="(value, i) in form.problemValues" v-if="i % 3 == 0" :key="i">
                        <f7-col v-for="j in 3" :key="i + '-' + j">
                            <f7-button v-if="i + j - 1 < form.problemValues.length" 
                                @click="pointClick(i + j - 1)"
                                :id="'value-image-btn-' + (i + j - 1)">
                                {{form.problemValues[i + j - 1].val}}
                            </f7-button>
                            <PopoverKeyboard :ref="'popoverKeyboard-' + (i + j - 1)" 
                                :index="i + j - 1" :count="form.problemValues.length"
                                @delete="pointDelete(i + j - 1)"
                                @next="nextPointClick(i + j - 1)"
                                @change="pointChange(i + j - 1, $event)">
                            </PopoverKeyboard>
                        </f7-col>
                    </f7-row>
                </f7-col>
            </f7-row>
            <f7-row style="margin-bottom:5px;">
                <f7-col width="30">
                    <span>合格率</span>
                </f7-col>
                <f7-col width="30">
                    <span>{{qualificationRate}}%</span>
                </f7-col>
                <f7-col v-if="qualityMeasureProblem && qualityMeasureProblem.repair_by == null" width="40">
                    <f7-checkbox :checked="form.repair != null" @change="toggleRepair"></f7-checkbox>&nbsp;&nbsp;通知整改
                </f7-col>
            </f7-row>
            <f7-row style="margin-bottom:5px;">
                <TakePhoto ref="refTakePhoto" @photoAdd="photoAdd" @photoDelete="photoDelete"></TakePhoto>
            </f7-row>
            <f7-list  inline-labels no-hairlines style="margin-top:5px; margin-bottom:5px;">
                <f7-list-item v-if="qualityMeasureProblem && qualityMeasureProblem.repair_by == null"  v-show="form.repair != null" 
                    id="repairUserSmartSelect-workbenchQualityMeasureProblemModify" 
                    smart-select
                    :smart-select-params="{openIn: 'popup', closeOnSelect: true, searchbar: true, searchbarPlaceholder: '搜索', searchbarDisableText: '取消', popupCloseLinkText: '返回'}">
                    <f7-label>整改人</f7-label>
                    <select v-model="form.repair">
                        <optgroup label="施工单位">
                            <option v-for="(userId, i) in contractors" :key="userId"
                                :value="userId" v-text="$store.state.global.userMap[userId].realname">
                            </option>
                        </optgroup>
                        <optgroup label="监理单位">
                            <option v-for="(userId, i) in supervisors" :key="userId"
                                :value="userId" v-text="$store.state.global.userMap[userId].realname">
                            </option>
                        </optgroup>
                        <optgroup label="建设单位">
                            <option v-for="(userId, i) in constructors" :key="userId"
                                :value="userId" v-text="$store.state.global.userMap[userId].realname">
                            </option>
                        </optgroup>
                    </select>
                </f7-list-item>
                <f7-list-item v-if="qualityMeasureProblem && qualityMeasureProblem.repair_by == null" id="ccUserSmartSelect-workbenchQualityMeasureProblemModify" smart-select
                    :smart-select-params="{openIn: 'popup', searchbar: true, searchbarPlaceholder: '搜索', searchbarDisableText: '取消', popupCloseLinkText: '返回'}">
                    <f7-label>抄送人</f7-label>
                    <select multiple v-model="form.ccs">
                        <optgroup label="施工单位">
                            <option v-for="(userId, i) in contractors" :key="userId"
                                :value="userId" v-text="$store.state.global.userMap[userId].realname">
                            </option>
                        </optgroup>
                        <optgroup label="监理单位">
                            <option v-for="(userId, i) in supervisors" :key="userId"
                                :value="userId" v-text="$store.state.global.userMap[userId].realname">
                            </option>
                        </optgroup>
                        <optgroup label="建设单位">
                            <option v-for="(userId, i) in constructors" :key="userId"
                                :value="userId" v-text="$store.state.global.userMap[userId].realname">
                            </option>
                        </optgroup>
                    </select>
                </f7-list-item>
                <f7-list-item>
                    <f7-list-button title="暂存" style="width:100%;" @click="saveTemporary">
                    </f7-list-button>
                    <f7-list-button title="提交" style="width:100%;" @click="submit" v-show="isOnline">
                    </f7-list-button>
                </f7-list-item>
            </f7-list>
        </f7-block>
    </f7-page>
</template>

<script>
import networkEvent from '@/mixins/networkEvent';
import back from '@/mixins/back.js';
import userCategory from '@/mixins/userCategory.js';
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import FileUtil from "@/utils/FileUtil.js";
import request from '@/utils/request';
import $ from 'jquery';
import events from 'events';
import store from '@/store';
import { getUser, setUser, clearUser } from '@/utils/auth';
import { upload, uploadImage } from '@/utils/upload';
import TakePhoto from "@/components/TakePhoto.vue";
import PopoverKeyboard from "@/components/PopoverKeyboard.vue";

export default {
    store: store,
    mixins: [networkEvent, back, userCategory],
    components: {
        TakePhoto,
        PopoverKeyboard
    },
    props: {
    	qualityMeasureProblem: {
    		type: Object
    	}
    },
    data: function() {
        return {
        	uuid: Common.uuid(),
        	isOnline: true,
            stepper: null,
            defaultRepair: null,
            form: {
                tid: null,
                qualityMeasureProblemId: null,
                measurePoints: 0,
                problemValues: [],
                regist: getUser().userId,
                repair: null,
                ccs: [],
                photos: []
            },
            deletePhotos: [],
            draftModifyProblem: null
        };
    },
    methods: {
        pageBeforeIn: function() {
            this.isOnline = Common.isOnline();
        },
        back: function() {
        	var self = this;
            this.$f7.dialog.confirm("", "你确定要退出吗？", function() {
                self.$f7router.back();
            });
        },
        pointCountChange: function() {
            this.form.measurePoints = this.stepper.getValue();
        },
        openHousePoint: function() {
            var self = this;
            var router = this.$f7router.navigate('/HousePoint', {
                props: {
                    imageUrl: this.qualityMeasureProblem.drawing_file.length > 0 ? this.qualityMeasureProblem.drawing_file[0].url : '',
                    pointCount: this.form.measurePoints,
                    initialPoints: this.form.problemValues,
                    overPointCountMessage: '爆点数不能超过测量点数',
                    hasPointValue: true
                }
            });
            router.off('pointAdd');
            router.on('pointAdd', function(point) {
                self.form.problemValues.push(point);
            });
            router.off('pointDelete');
            router.on('pointDelete', function(point) {
                for(var i = 0; i < self.form.problemValues.length; i++) {
                    if(point.x == self.form.problemValues[i].x
                        && point.y == self.form.problemValues[i].y) {
                        self.form.problemValues.splice(i, 1);
                        break;
                    }
                }
            });
            router.off('pointChange');
            router.on('pointChange', function(point) {
                for(var i = 0; i < self.form.problemValues.length; i++) {
                    if(point.x == self.form.problemValues[i].x
                        && point.y == self.form.problemValues[i].y) {
                        self.form.problemValues.splice(i, 1, point);
                        break;
                    }
                }
            });
        },
        addProblemValue: function() {
            if(this.form.problemValues.length >= this.form.measurePoints) {
                this.$f7.dialog.alert('', '爆点数不能超过实测点数');
                return;
            }
            var problemValue = {
                val: null
            }
            this.form.problemValues.push(problemValue);
        },
        pointClick: function(index) {
            this.$refs['popoverKeyboard-' + index][0].open('#value-image-btn-' + index);
        },
        pointDelete: function(index) {
            this.form.problemValues.splice(index, 1);
        },
        nextPointClick: function(index) {
            this.$refs['popoverKeyboard-' + index][0].close();
            this.pointClick(index + 1);
        },
        pointChange: function(index, value) {
            this.form.problemValues[index].val = value;
        },
        toggleRepair: function() {
            if(this.form.repair != null) {
                this.form.repair = null;
            } else {
                if(this.defaultRepair == null) {
                    this.form.repair = '';
                } else {
                    this.form.repair = this.defaultRepair;
                }
            }
        },
        photoAdd: function(cdvPath) {
            this.form.photos.push(cdvPath);
        },
        photoDelete: function(cdvPath) {
            for(var i = 0; i < this.form.photos.length; i++) {
                if(cdvPath == this.form.photos[i]) {
                    this.form.photos.splice(i, 1);
                    if(cdvPath.indexOf('qualityMeasure') > -1) {
                        this.deletePhotos.push(cdvPath);
                    }
                    break;
                }
            }
        },
        saveModify: function(successCallback, failureCallback) {
        	var self = this;
            self.$f7.preloader.show();
            let promises = [];
            self.deletePhotos.forEach(photo => {
    	        let promise = FileUtil.remove(photo).then(() => {
    	        	return Promise.resolve();
    	        }).catch((error) => {
    	        	console.error(error);
    	        	return Promise.resolve();
    	        });
    	        promises.push(promise);
    		});
            Promise.all(promises).then(() => {
    			let promises = [];
    			self.form.photos.forEach(photo => {
    				let promise = null;
    				if(photo.indexOf(Common.directory().qualityMeasure) < 0) {
    					let splits = photo.split('/');
    					let filename = splits[splits.length - 1];
    					let to = Common.directory().base + Common.directory().qualityMeasure + filename;
    					promise = FileUtil.copy(photo, to);
    				} else {
    					promise = new Promise((resolve, reject) => {
    						resolve(photo);
    					});
    				}
                    promises.push(promise);
    			});
    			return Promise.all(promises);
            }).then(() => {
            	let sql = "";
            	if(self.form.tid == null) {
                    sql = "\
                        insert into tmp_quality_measure_checkquality_problem_modify( \
                        quality_measure_checkquality_problem_id, regist, repair, ccs, \
                        measure_points, problem_values, photos) \
                        values (?, ?, ?, ?, ?, ?, ?) \
                    ";  
                } else {
                    sql = "\
                        update tmp_quality_measure_checkquality_problem_modify \
                        set quality_measure_checkquality_problem_id = ?, regist = ?, repair = ?, ccs = ?, \
                        measure_points = ?, problem_values = ?, photos = ? \
                        where tid = '" + self.form.tid + "' \
                    ";
                }
                var values = [
                	self.form.qualityMeasureProblemId,
                	self.form.regist,
                	self.form.repair,
                    JSON.stringify(self.form.ccs),
                    self.form.measurePoints,
                    JSON.stringify(self.form.problemValues),
                    JSON.stringify(self.form.photos)
                ];
                
                return Common.executeSql(sql, values);
            }).then((result) => {
            	let rs = result.rs;
            	let tid = self.form.tid == null ? rs.insertId : self.form.tid;
            	var logStr = (self.form.tid == null ? 'insert' : 'update') 
	                + " tmp_quality_measure_checkquality_problem_modify success! tid: "
	                + tid;
            
	            console.log(logStr);
	            successCallback(tid);
	            let sql = "\
            	    select * from tmp_quality_measure_checkquality_problem_modify \
            	    where tid = '" + tid + "' \
            	";
                return Common.executeSql(sql, []);
            }).then((result) => {
            	let rs = result.rs;
            	var row = rs.rows.item(0);
                self.$f7router.emit('qualityMeasureModify', {
                	'problemId': row.quality_measure_checkquality_problem_id,
                	'value': row
                });
                self.$f7.preloader.hide();
            }).catch(error => {
            	console.error(error);
            	failureCallback();
            	self.$f7.preloader.hide();
            });
            
            /* var photos = [];
            var fileTransfer = new window.parent.FileTransfer();
            for(var i = 0; i < self.form.photos.length; i++) {
                var photo = self.form.photos[i];
                if(photo.indexOf('qualityMeasure') == -1) {
                    var splits = photo.split("/");
                    var filename = splits[splits.length - 1];
                    var localPath = 
                        window.parent.cordova.file.dataDirectory + Common.qualityMeasureDirectory + "/" + filename;
                    photos.push(Common.localPathToCdv(localPath));
                    window.parent.download(photo, localPath);
                } else {
                    photos.push(photo);
                }
            }
            self.form.photos = photos;
            window.parent.saveTmpQualityMeasureProblemModify(self.form, function(tid) {
                successCallback(tid);
                window.parent.db.transaction(function(tx) {
                	var sql = "\
                	    select * from tmp_quality_measure_checkquality_problem_modify \
                	    where tid = '" + tid + "' \
                	";
                	tx.executeSql(sql, [], function(tx, rs) {
                		var row = rs.rows.item(0);
                        self.$f7router.emit('qualityMeasureModify', {
                        	'problemId': row.quality_measure_checkquality_problem_id,
                        	'value': row
                        });
                	});
                }, function(error) {
                	console.error(error);
                });
                self.$f7.preloader.hide();
            }, function() {
            	failureCallback();
                self.$f7.preloader.hide();
            }); */
        },
        saveTemporary: function() {
        	var self = this;
        	this.saveModify(function(tid) {
                self.$f7.dialog.alert('', '暂存问题成功！');
                self.$emit('saveTemporary', tid);
                self.$f7router.emit('saveTemporary', tid);
                self.$f7router.back();
        	}, function() {
                self.$f7.dialog.alert('', '暂存问题失败！');
        	});
        },
        submit: function() {
            var self = this;
            if(this.form.repair == '') {
                this.$f7.dialog.alert('', '请选择整改人');
            }
            this.$f7.dialog.confirm('', '确定提交吗?', function() {
                //self.$f7.preloader.show();
                let dialog = self.$f7.dialog.progress('上传图片中', 0);
                let problem = null;
                let promises = [];
                self.deletePhotos.forEach(photo => {
        	        let promise = FileUtil.remove(photo).then(() => {
        	        	return Promise.resolve();
        	        }).catch((error) => {
        	        	console.error(error);
        	        	return Promise.resolve();
        	        });
        	        promises.push(promise);
        		});
                var data = new FormData();
                Promise.all(promises).then(() => {
                	let promises = [];
                    data.append("qualityMeasureProblemId", self.form.qualityMeasureProblemId);
                    data.append("measurePoints", self.form.measurePoints);
                    data.append("regist", self.form.regist);
                    var selfVm = self;
                    self.form.problemValues.forEach(function(problemValue) {
                        data.append('values', problemValue.val);
                        if(selfVm.qualityMeasureProblem.drawing_file.length > 0) {
                            data.append('pointsX', problemValue.x);
                            data.append('pointsY', problemValue.y);
                        }
                    });
                    for(var i = 0; i < self.form.photos.length; i++) {
                        data.append("photos", self.form.photos[i]);
                    }
                    if(self.form.repair != null) {
                        data.append("repair", self.form.repair);
                    }
                    self.form.ccs.forEach(function(cc) {
                        data.append('ccs', cc);
                    });
                    self.form.photos.forEach(photoPath => {
                    	let promise = FileUtil.read(photoPath, 'image/jpeg').then(blob => {
                    		let splits = photoPath.split("/");
                    		let filename = splits[splits.length - 1];
                    		return uploadImage(filename, blob);
                    	}).then(result => {
                    		data.photos.push({url: result.url});
                    		dialog.finishCount++;
                    		dialog.setProgress(parseInt(dialog.finishCount / (self.form.photos.length + 1)) * 100);
                    		return Promise.resolve();
                    	}).catch((error) => {
                    		console.error(error);
                    		return Promise.resolve();
                    	});
                    	promises.push(promise);
                    });
                    return Promise.all(promises);
                }).then(() => {
                	return request({
                		url: '/rest/api/v3/qualityMeasureCheckQualityProblem/modify',
                		method: 'post',
                		data: data
                	});
                }).then(data => {
                	problem = data.element;
                	let promises = [];
                	self.form.photos.forEach(photo => {
            	        let promise = FileUtil.remove(photo).then(() => {
            	        	return Promise.resolve();
            	        }).catch((error) => {
            	        	console.error(error);
            	        	return Promise.resolve();
            	        });
            	        promises.push(promise);
            		});
                	return Promise.all(promises);
                }).then(() => {
                	let promises = [];
                	let promise = null;
                	if(self.form.tid != null) {
                		let sql = "\
                            delete from tmp_quality_measure_checkquality_problem_modify \
                            where tid = '" + self.form.tid + "' \
                        ";
                		promise = Common.executeSql(sql, []);
                		promises.push(promise);
                        self.$f7router.emit('qualityMeasureModify', {
                        	'problemId': self.form.qualityMeasureProblemId,
                        	'value': null
                        });
                    }
                	return Promise.all(promises);
                }).then(() => {
                	let sql = 
            			"select quality_measure_checkquality_problem_id, update_time " +
            			"from tb_quality_measure_checkquality_problem t " +
            			"where item_id = '" + problem.itemId + "' ";
                	return Common.executeSql(sql, []);
                }).then((result) => {
                	let problems = [];
                	let rs = result.rs;
                	let localMap = {};
                    for(var i = 0; i < rs.rows.length; i++) {
                        var row = rs.rows.item(i);
                        var item = {};
                        item.quality_measure_checkquality_problem_id = row['quality_measure_checkquality_problem_id'];
                        item.update_time = row['update_time'];
                        localMap[item.quality_measure_checkquality_problem_id] = item;
                    }
                    let elements = [problem];
                    for(var i = 0; i < problems.length; i++) {
                    	var element = problems[i];
                    	if(localMap[element.entityId] && localMap[element.entityId].update_time != element.updateTimestamp) {
                    		elements.push(element);
                    	}
                    }
                    let sql = 
                        "update tb_quality_measure_checkquality_problem set " +
                        "update_time = ?, batch_type = ?, drawing_file = ?, image_file = ?, measure_points = ?, " +
                        "problem_points = ?, problem_values = ?, regist_date = ?, remark = ?, repair_date = ?, " +
                        "repair_image_file = ?, repair_remark = ?, sent_back_date = ?, sent_back_image_file = ?, " +
                        "sent_back_remark = ?, sent_back_times = ?, small_image_file = ?, " +
                        "small_repair_image_file = ?, small_sent_back_image_file = ?, standard_min = ?, standard_max = ?, " +
                        "status = ?, building_id = ?, floor_id = ?, room_id = ?, item_id = ?, regist_by = ?, repair_by = ?, " +
                        "unit_id = ?, app_permission = ?, ccs = ? " +
                        "where quality_measure_checkquality_problem_id = ?";
                    let batchSql = [];
                    for(var i = 0; i < elements.length; i++) {
                		var element = elements[i];
                		var values = [
                			element.updateTimestamp,
                			element.batchType,
                			element.drawingFile,
                			element.imageFile,
                			element.measurePoints,
                			element.problemPoints,
                			element.problemValues,
                			element.registTimestamp,
                			element.remark,
                			element.repairTimestamp,
                			element.repairImageFile,
                			element.repairRemark,
                			element.sentBackTimestamp,
                			element.sentBackImageFile,
                			element.sentBackRemark,
                			element.sentBackTimes,
                			element.smallImageFile,
                			element.smallRepairImageFile,
                			element.smallSentBackImageFile,
                			element.standardMin,
                			element.standardMax,
                			element.status,
                			element.buildingId,
                			element.floorId,
                			element.roomId,
                			element.itemId,
                			element.registBy,
                			element.repairBy,
                			element.unitId,
                			element.appPermission,
                			element.ccs,
                			element.entityId
                        ];
            			batchSql[i] = [sql, values];
                    }
                    return Common.sqlBatch(batchSql);
                }).then(() => {
                	return request({
                		url: '/rest/api/v3/qualityMeasureCheckQualityRepair/findByQualityMeasureProblemId',
                		method: 'GET',
                		data: {
                            qualityMeasureProblemId: problem.entityId
                        }
                	});
                }).then((data) => {
                	let repairs = data.elements;
                	let sql = "\
                        delete from tb_quality_measure_checkquality_repair \
                        where quality_measure_checkquality_problem_id = '" + problem.entityId + "' \
                    ";
                	let promise = Common.executeSql(sql, []).then(() => {
                		let sql = 
                			"select quality_measure_checkquality_repair_id, update_time " +
                			"from tb_quality_measure_checkquality_repair t ";
                		return Common.executeSql(sql, []);
                	}).then((result) => {
                		let rs = result.rs;
                		let localMap = {};
                        for(var i = 0; i < rs.rows.length; i++) {
                            var row = rs.rows.item(i);
                            var item = {};
                            item.quality_measure_checkquality_repair_id = row['quality_measure_checkquality_repair_id'];
                            item.update_time = row['update_time'];
                            localMap[item.quality_measure_checkquality_repair_id] = item;
                        }
                        let elements = [];
                        for(var i = 0; i < repairs.length; i++) {
                        	let element = repairs[i];
                        	if(localMap[element.entityId] == null) {
                        		elements.push(element);
                        	}
                        }
                        let sql = 
                            "insert into tb_quality_measure_checkquality_repair ( " +
                            "quality_measure_checkquality_repair_id, update_time, has_read, reading_time, " +
                            "quality_measure_checkquality_problem_id, child_qualityMeasureCheckQualityRepair_id, " +
                            "parent_qualityMeasureCheckQualityRepair_id, repair) " +
                            "values (?, ?, ?, ?, ?, ?, ?, ?) ";
                        let batchSql = [];
                        for(var i = 0; i < elements.length; i++) {
                    		var element = elements[i];
                			var values = [
                				element.entityId,
                    			element.updateTimestamp,
                    			element.hasRead,
                    			element.readingTime,
                    			element.qualityMeasureCheckqualityProblemId,
                    			element.childQualityMeasureCheckQualityRepairId,
                    			element.parentQualityMeasureCheckQualityRepairId,
                    			element.repair
                            ];
                			batchSql[i] = [sql, values];
                        }
                        return Common.sqlBatch(batchSql);
                	})
                	return promise;
                }).then((result) => {
                	dialog.close();
                	self.$f7.dialog.alert('', '提交问题成功!');
                    self.$f7.preloader.hide();
                    self.$f7router.back();
                }).catch(error => {
                	dialog.close();
                	console.error(error);
                	self.$f7.dialog.alert('', '提交失败，问题已暂存到手机!');
                    self.saveTemporary();
                    self.$f7.preloader.hide();
                    self.$f7router.back();
                });
                
                
                /* for(var i = 0; i < self.deletePhotos.length; i++) {
                    var cdvPath = self.deletePhotos[i];
                    var splits = cdvPath.split("/");
                    var filename = splits[splits.length - 1];
                    (function(filename) {
                        window.parent.resolveLocalFileSystemURL(window.parent.cordova.file.dataDirectory, function(fs) {
                            fs.getDirectory(Common.qualityMeasureDirectory, {create: false}, function(dirEntry) {
                                dirEntry.getFile(filename, {create: false, exclusive: false}, function(fileEntry) {
                                    fileEntry.remove();
                                }, function(error) {
                                    console.error(error);
                                });
                            }, function(error) {
                                console.error(error);
                            });
                        }, function(error) {
                            console.error(error);
                        });
                    })(filename);
                }
                var data = new FormData();
                data.append("qualityMeasureProblemId", self.form.qualityMeasureProblemId);
                data.append("measurePoints", self.form.measurePoints);
                data.append("regist", self.form.regist);
                var selfVm = self;
                self.form.problemValues.forEach(function(problemValue) {
                    data.append('values', problemValue.val);
                    if(selfVm.qualityMeasureProblem.drawing_file.length > 0) {
                        data.append('pointsX', problemValue.x);
                        data.append('pointsY', problemValue.y);
                    }
                });
                for(var i = 0; i < self.form.photos.length; i++) {
                    data.append("photos", self.form.photos[i]);
                }
                if(self.form.repair != null) {
                    data.append("repair", self.form.repair);
                }
                self.form.ccs.forEach(function(cc) {
                    data.append('ccs', cc);
                });
                var readerTags = self.form.photos.map(function(photo) {
                    return false;
                });
                var emitter = new events.EventEmitter();
                emitter.on('readFinish', function() {
                    for(var i = 0; i < readerTags.length; i++) {
                        if(!readerTags[i]) {
                            return;
                        }
                    }
                    Common.ajax({
                        type: 'POST',
                        url: Common.address +  '/rest/api/v3/qualityMeasureCheckQualityProblem/modify',
                        data: data,
                        xhrFields: {
                            withCredentials: true
                        },
                        cache: false,
                        processData: false,
                        contentType: false,
                        dataType: "json",
                        success: function(result) {
                            self.$f7.dialog.alert('', '提交问题成功!');
                            for(var i = 0; i < self.form.photos.length; i++) {
                                var cdvPath = self.form.photos[i];
                                var splits = cdvPath.split("/");
                                var filename = splits[splits.length - 1];
                                (function(filename) {
                                    window.parent.resolveLocalFileSystemURL(window.parent.cordova.file.dataDirectory, function(fs) {
                                        fs.getDirectory(Common.qualityMeasureDirectory, {create: false}, function(dirEntry) {
                                            dirEntry.getFile(filename, {create: false, exclusive: false}, function(fileEntry) {
                                                fileEntry.remove();
                                            }, function(error) {
                                                console.error(error);
                                            });
                                        }, function(error) {
                                            console.error(error);
                                        });
                                    }, function(error) {
                                        console.error(error);
                                    });
                                })(filename);
                            }
                            if(self.form.tid != null) {
                                window.parent.db.transaction(function(tx) {
                                    var sql = "\
                                        delete from tmp_quality_measure_checkquality_problem_modify \
                                        where tid = '" + self.form.tid + "' \
                                    ";
                                    tx.executeSql(sql, [], function(tx, rs) {
                                        
                                    });
                                });
                                self.$f7router.emit('qualityMeasureModify', {
                                	'problemId': self.form.qualityMeasureProblemId,
                                	'value': null
                                });
                            }
                            (function(problem) {
                            	var emitter = new events.EventEmitter();
                                emitter.on('updateQualityMeasureCheckQualityProblemsByItemId', function() {
                                    Common.ajax({
                                        url: Common.address + '/rest/api/v3/qualityMeasureCheckQualityRepair/findByQualityMeasureProblemId',
                                        type: 'GET',
                                        xhrFields: {
                                            withCredentials: true
                                        },
                                        data: {
                                            qualityMeasureProblemId: problem.entityId
                                        },
                                        timeout: 60000,
                                        success: function(result) {
                                            var emitter = new events.EventEmitter();
                                            emitter.once('insertQualityMeasureCheckQualityRepairs', function() {
                                                window.parent.db.transaction(function(tx) {
                                                    var sql = "\
                                                        select t.*, p.repair \
                                                        from tb_quality_measure_checkquality_problem t \
                                                        left join tb_quality_measure_checkquality_repair p \
                                                        on t.quality_measure_checkquality_problem_id = p.quality_measure_checkquality_problem_id \
                                                        where p.child_qualityMeasureCheckQualityRepair_id is null \
                                                        and t.quality_measure_checkquality_problem_id = '" + problem.entityId + "' \
                                                    ";
                                                    tx.executeSql(sql, [], function(tx, rs) {
                                                        self.$f7.preloader.hide();
                                                        self.$f7router.back();
                                                    });
                                                }, function(error) {
                                                    console.error(error);
                                                    self.$f7.preloader.hide();
                                                    self.$f7router.back();
                                                });
                                            });
                                            emitter.once('deleteQualityMeaureRepairs', function() {
                                                window.parent.insertQualityMeasureCheckQualityRepairs(result.elements, emitter);
                                            });
                                            window.parent.db.transaction(function(tx) {
                                                var sql = "\
                                                    delete from tb_quality_measure_checkquality_repair \
                                                    where quality_measure_checkquality_problem_id = '" + problem.entityId + "' \
                                                ";
                                                tx.executeSql(sql, [], function(tx, rs) {
                                                    emitter.emit('deleteQualityMeaureRepairs');
                                                });
                                            }, function(error) {
                                                console.error(error);
                                                emitter.emit('deleteQualityMeaureRepairs');
                                            })
                                        },
                                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                                            self.$f7.preloader.hide();
                                            self.$f7router.back();
                                        }
                                    });
                                });
                                window.parent.updateQualityMeasureCheckQualityProblemsByItemId(
                                    [problem], problem.itemId, emitter);
                            })(result.element);
                        },
                        error: function() {
                            self.$f7.dialog.alert('', '提交失败，问题已暂存到手机!');
                            self.saveTemporary();
                            self.$f7.preloader.hide();
                            self.$f7router.back();
                        }
                    });
                });
                if(self.form.photos.length > 0) {
                    for(var i = 0; i < self.form.photos.length; i++) {
                        (function(index) {
                            var photo = self.form.photos[index];
                            var xhr = new XMLHttpRequest();
                            xhr.open('GET', photo, true);
                            xhr.responseType = 'blob';
                            xhr.onload = function() {
                                if(this.status == 200) {
                                    var blob = new Blob([this.response], {type: 'image/jpeg'});
                                    data.append('photos', blob);
                                    readerTags[index] = true;
                                    emitter.emit('readFinish');
                                }
                            };
                            xhr.send();
                        })(i);
                    }   
                } else {
                    emitter.emit('readFinish');
                }*/
            }); 
        }
    },
    computed: {
        qualificationRate: function() {
            if(this.form.measurePoints == 0) {
                return 0;
            }
            var rate = 1 - this.form.problemValues.length / this.form.measurePoints;
            return (rate * 100).toFixed(1);
        }
    },
    watch: {
    	'form.measurePoints': function(newVal, oldVal) {
    		this.stepper.setValue(this.form.measurePoints);
            while(this.form.problemValues.length > this.form.measurePoints) {
                this.form.problemValues.pop();
            }
    	},
    	'form.repair': function(newVal, oldVal) {
    		if(this.form.repair == null || this.form.repair == '') {
    			 //由于v-if和v-show显示冲突无法构造页面因此修改代码
    			var smartSelect = this.$f7.smartSelect
    				.get('#repairUserSmartSelect-workbenchQualityMeasureProblemModify .smart-select');
    			if(smartSelect){
    				smartSelect.setValue('');
    			}
    		} else {
                var self = this;
                //由于v-if和v-show显示冲突无法构造页面因此修改代码
                var smartSelect = this.$f7.smartSelect
					.get('#repairUserSmartSelect-workbenchQualityMeasureProblemModify .smart-select');
                if(smartSelect){
    				smartSelect.setValue(
    	                	this.$store.state.global.userMap[this.form.repair].realname
                    );
    			}
    		}
    	},
        'form.ccs': function(newVal, oldVal) {
        	if(this.form.ccs != null) {
                var self = this;
                //由于v-if和v-show显示冲突无法构造页面因此修改代码
                var smartSelect = this.$f7.smartSelect
                	.get('#ccUserSmartSelect-workbenchQualityMeasureProblemModify .smart-select');
                if(smartSelect) {
                	smartSelect.setValue(
                        self.form.ccs.map(function(cc) {
                            return self.$store.state.global.userMap[cc].realname;
                        }).join(',')
                    );	
                }
        	}
        }
    },
    created: function() {
    	var self = this;
    	this.form.qualityMeasureProblemId = this.qualityMeasureProblem.id;
    	var problemClassIds = this.$store.state.global.bidSectionCheckItemRel.bidSectionMap[this.qualityMeasureProblem.bid_section_id];
    	for(var itemId in problemClassIds){
    		var bidSectionCheckItem = this.$store.state.global.bidSectionCheckItemRel[problemClassIds[itemId]];
            if(bidSectionCheckItem.bid_section_id == this.qualityMeasureProblem.bid_section_id &&
                bidSectionCheckItem.check_item_id == this.qualityMeasureProblem.item_id) {
                self.defaultRepair = bidSectionCheckItem.repair;
                break;
            }
    	}
        let sql = "\
            select * from tmp_quality_measure_checkquality_problem_modify t \
            where t.quality_measure_checkquality_problem_id = '" + self.form.qualityMeasureProblemId + "' \
        ";
        Common.executeSql(sql, []).then((result) => {
    		let rs = result.rs;
    		if(rs.rows.length == 0) {
            	self.form.measurePoints = self.qualityMeasureProblem.measure_points;
                self.form.problemValues = Common.strToJson(self.qualityMeasureProblem.problem_values);
                self.form.regist = self.qualityMeasureProblem.regist_by;
                self.form.repair = self.qualityMeasureProblem.repair;
                self.form.ccs = Common.strToJson(self.qualityMeasureProblem.ccs);
                self.form.photos = 
                	Common.strToJson(self.qualityMeasureProblem.image_file).map(function(imageFile) {
                	    return imageFile.url;
                	});
                self.saveModify(function(tid) {
                	self.form.tid = tid;
                }, function() {});
            } else {
            	var row = rs.rows.item(0);
            	self.form.tid = row.tid;
                self.form.measurePoints = row.measure_points;
                self.form.problemValues = Common.strToJson(row.problem_values);
                self.form.regist = row.regist;
                self.form.repair = row.repair;
                self.form.ccs = Common.strToJson(row.ccs);
                self.form.photos = Common.strToJson(row.photos);
            }
            self.$refs['refTakePhoto'].addPhotos(self.form.photos);
        }).catch(error => {
			console.error(error);
		});	
        
    },
    mounted: function() {
        var self = this;
        self.stepper = self.$f7.stepper.get('.stepper');
    }
}
</script>

<style scoped>

</style>